<!DOCTYPE html>
<html lang="zh-CN">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: light)">
<meta name="theme-color" content="#222" media="(prefers-color-scheme: dark)"><meta name="generator" content="Hexo 5.2.0">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">



<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.2/css/all.min.css" integrity="sha256-xejo6yLi6vGtAjcMIsY8BHdKsLg7QynVlFMzdQgUuy8=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.1.1/animate.min.css" integrity="sha256-PR7ttpcvz8qrF57fur/yAx1qXMFJeJFiA6pSzWi0OIE=" crossorigin="anonymous">
  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.css" integrity="sha256-Vzbj7sDDS/woiFS3uNKo8eIuni59rjyNGtXfstRzStA=" crossorigin="anonymous">

<script class="next-config" data-name="main" type="application/json">{"hostname":"gz1234.gitee.io","root":"/","images":"/images","scheme":"Gemini","darkmode":true,"version":"8.12.3","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12},"copycode":{"enable":true,"style":"flat"},"bookmark":{"enable":true,"color":"#222","save":"auto"},"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"stickytabs":false,"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"fadeInDown","post_body":"fadeInDown","coll_header":"fadeInLeft","sidebar":"fadeInUp"}},"prism":false,"i18n":{"placeholder":"搜索...","empty":"没有找到任何搜索结果：${query}","hits_time":"找到 ${hits} 个搜索结果（用时 ${time} 毫秒）","hits":"找到 ${hits} 个搜索结果"},"path":"/search.xml","localsearch":{"enable":true,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false}}</script><script src="/js/config.js"></script>

    <meta name="description" content="路由的使用本章我们来介绍react中路由的使用,现在使用的路由是React-Router-4版本,我们需要下载的包叫react-router-dom 安装1npm install react-router-dom">
<meta property="og:type" content="article">
<meta property="og:title" content="react 路由的使用">
<meta property="og:url" content="https://gz1234.gitee.io/2020/10/22/react%E7%AC%94%E8%AE%B0/React%E8%B7%AF%E7%94%B1/index.html">
<meta property="og:site_name" content="郭泽">
<meta property="og:description" content="路由的使用本章我们来介绍react中路由的使用,现在使用的路由是React-Router-4版本,我们需要下载的包叫react-router-dom 安装1npm install react-router-dom">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2020-10-22T02:07:09.000Z">
<meta property="article:modified_time" content="2021-10-13T10:11:55.287Z">
<meta property="article:author" content="郭泽">
<meta property="article:tag" content="react 基础">
<meta name="twitter:card" content="summary">


<link rel="canonical" href="https://gz1234.gitee.io/2020/10/22/react%E7%AC%94%E8%AE%B0/React%E8%B7%AF%E7%94%B1/">



<script class="next-config" data-name="page" type="application/json">{"sidebar":"","isHome":false,"isPost":true,"lang":"zh-CN","comments":true,"permalink":"https://gz1234.gitee.io/2020/10/22/react%E7%AC%94%E8%AE%B0/React%E8%B7%AF%E7%94%B1/","path":"2020/10/22/react笔记/React路由/","title":"react 路由的使用"}</script>

<script class="next-config" data-name="calendar" type="application/json">""</script>
<title>react 路由的使用 | 郭泽</title>
  





  <noscript>
    <link rel="stylesheet" href="/css/noscript.css">
  </noscript>
</head>

<body itemscope itemtype="http://schema.org/WebPage" class="use-motion">
  <div class="headband"></div>

  <main class="main">
    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="切换导航栏" role="button">
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
        <span class="toggle-line"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <i class="logo-line"></i>
      <p class="site-title">郭泽</p>
      <i class="logo-line"></i>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
        <i class="fa fa-search fa-fw fa-lg"></i>
    </div>
  </div>
</div>



<nav class="site-nav">
  <ul class="main-menu menu"><li class="menu-item menu-item-home"><a href="/" rel="section"><i class="fa fa-home fa-fw"></i>首页</a></li><li class="menu-item menu-item-about"><a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>关于</a></li><li class="menu-item menu-item-tags"><a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>标签</a></li><li class="menu-item menu-item-categories"><a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>分类</a></li><li class="menu-item menu-item-archives"><a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>归档</a></li>
      <li class="menu-item menu-item-search">
        <a role="button" class="popup-trigger"><i class="fa fa-search fa-fw"></i>搜索
        </a>
      </li>
  </ul>
</nav>



  <div class="search-pop-overlay">
    <div class="popup search-popup"><div class="search-header">
  <span class="search-icon">
    <i class="fa fa-search"></i>
  </span>
  <div class="search-input-container">
    <input autocomplete="off" autocapitalize="off" maxlength="80"
           placeholder="搜索..." spellcheck="false"
           type="search" class="search-input">
  </div>
  <span class="popup-btn-close" role="button">
    <i class="fa fa-times-circle"></i>
  </span>
</div>
<div class="search-result-container no-result">
  <div class="search-result-icon">
    <i class="fa fa-spinner fa-pulse fa-5x"></i>
  </div>
</div>

    </div>
  </div>

</div>
        
  
  <div class="toggle sidebar-toggle" role="button">
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
    <span class="toggle-line"></span>
  </div>

  <aside class="sidebar">

    <div class="sidebar-inner sidebar-nav-active sidebar-toc-active">
      <ul class="sidebar-nav">
        <li class="sidebar-nav-toc">
          文章目录
        </li>
        <li class="sidebar-nav-overview">
          站点概览
        </li>
      </ul>

      <div class="sidebar-panel-container">
        <!--noindex-->
        <div class="post-toc-wrap sidebar-panel">
            <div class="post-toc animated"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#%E8%B7%AF%E7%94%B1%E7%9A%84%E4%BD%BF%E7%94%A8"><span class="nav-number">1.</span> <span class="nav-text">路由的使用</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%89%E8%A3%85"><span class="nav-number">1.1.</span> <span class="nav-text">安装</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%AE%B9%E5%99%A8%E7%BB%84%E4%BB%B6%E7%9A%84%E5%8C%BA%E5%88%AB"><span class="nav-number">1.2.</span> <span class="nav-text">容器组件的区别</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B7%91%E9%80%9A%E5%9F%BA%E6%9C%AC%E8%B7%AF%E7%94%B1"><span class="nav-number">1.3.</span> <span class="nav-text">跑通基本路由</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B7%AF%E7%94%B1%E7%9A%84%E5%8C%B9%E9%85%8D"><span class="nav-number">1.4.</span> <span class="nav-text">路由的匹配</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Link%E7%BB%84%E4%BB%B6"><span class="nav-number">1.5.</span> <span class="nav-text">Link组件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%A2%9E%E5%8A%A0%E5%AF%BC%E8%88%AA"><span class="nav-number">1.6.</span> <span class="nav-text">增加导航</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E9%A1%B5%E9%9D%A2%E7%BA%A7%E7%BB%84%E4%BB%B6"><span class="nav-number">1.7.</span> <span class="nav-text">页面级组件</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E4%BA%8C%E7%BA%A7%E8%B7%AF%E7%94%B1"><span class="nav-number">1.8.</span> <span class="nav-text">二级路由</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E4%BA%8C%E7%BA%A7%E8%B7%AF%E7%94%B1"><span class="nav-number">1.8.1.</span> <span class="nav-text">实现二级路由</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#UserList%E5%92%8CAdd%E7%BB%84%E4%BB%B6"><span class="nav-number">1.8.2.</span> <span class="nav-text">UserList和Add组件</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B7%AF%E7%94%B1%E8%B7%B3%E8%BD%AC%E5%92%8C%E8%B7%AF%E5%BE%84%E5%8F%82%E6%95%B0"><span class="nav-number">1.9.</span> <span class="nav-text">路由跳转和路径参数</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0%E6%B7%BB%E5%8A%A0%E7%94%A8%E6%88%B7"><span class="nav-number">1.9.1.</span> <span class="nav-text">实现添加用户</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%88%97%E8%A1%A8%E9%A1%B5%E5%B1%95%E7%A4%BA"><span class="nav-number">1.9.2.</span> <span class="nav-text">列表页展示</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%BC%95%E5%85%A5UserDetail%E7%BB%84%E4%BB%B6"><span class="nav-number">1.9.3.</span> <span class="nav-text">引入UserDetail组件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#UserDetail%E8%AF%A6%E6%83%85%E9%A1%B5"><span class="nav-number">1.9.4.</span> <span class="nav-text">UserDetail详情页</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%B7%AF%E7%94%B1%E5%8C%B9%E9%85%8D"><span class="nav-number">1.10.</span> <span class="nav-text">路由匹配</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B0%E5%A2%9E%E8%B7%AF%E7%94%B1%E5%8C%B9%E9%85%8D"><span class="nav-number">1.10.1.</span> <span class="nav-text">新增路由匹配</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#exact"><span class="nav-number">1.10.2.</span> <span class="nav-text">exact</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#Switch"><span class="nav-number">1.10.3.</span> <span class="nav-text">Switch</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%97%E4%BF%9D%E6%8A%A4%E7%9A%84%E8%B7%AF%E7%94%B1"><span class="nav-number">1.11.</span> <span class="nav-text">受保护的路由</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E5%8F%97%E4%BF%9D%E6%8A%A4%E8%B7%AF%E7%94%B1"><span class="nav-number">1.12.</span> <span class="nav-text">受保护路由</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#Protected%E7%BB%84%E4%BB%B6"><span class="nav-number">1.12.1.</span> <span class="nav-text">Protected组件</span></a></li><li class="nav-item nav-level-4"><a class="nav-link" href="#%E6%96%B0%E5%A2%9ELogin%E7%BB%84%E4%BB%B6"><span class="nav-number">1.12.2.</span> <span class="nav-text">新增Login组件</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#%E8%87%AA%E5%AE%9A%E4%B9%89%E8%8F%9C%E5%8D%95"><span class="nav-number">1.13.</span> <span class="nav-text">自定义菜单</span></a><ol class="nav-child"><li class="nav-item nav-level-4"><a class="nav-link" href="#%E5%AE%9E%E7%8E%B0MenuLink%E7%BB%84%E4%BB%B6"><span class="nav-number">1.13.1.</span> <span class="nav-text">实现MenuLink组件</span></a></li></ol></li><li class="nav-item nav-level-3"><a class="nav-link" href="#Prompt"><span class="nav-number">1.14.</span> <span class="nav-text">Prompt</span></a></li></ol></li><li class="nav-item nav-level-2"><a class="nav-link" href="#NotFound%E9%A1%B5%E9%9D%A2"><span class="nav-number">2.</span> <span class="nav-text">NotFound页面</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#%E6%96%B0%E5%A2%9E404%E8%B7%AF%E7%94%B1"><span class="nav-number">2.1.</span> <span class="nav-text">新增404路由</span></a></li></ol></li></ol></div>
        </div>
        <!--/noindex-->

        <div class="site-overview-wrap sidebar-panel">
          <div class="site-author site-overview-item animated" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">郭泽</p>
  <div class="site-description" itemprop="description"></div>
</div>
<div class="site-state-wrap site-overview-item animated">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
        <a href="/archives/">
          <span class="site-state-item-count">54</span>
          <span class="site-state-item-name">日志</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
          <a href="/categories/">
        <span class="site-state-item-count">21</span>
        <span class="site-state-item-name">分类</span></a>
      </div>
      <div class="site-state-item site-state-tags">
          <a href="/tags/">
        <span class="site-state-item-count">51</span>
        <span class="site-state-item-name">标签</span></a>
      </div>
  </nav>
</div>



        </div>
      </div>
    </div>
  </aside>
  <div class="sidebar-dimmer"></div>


    </header>

    
  <div class="back-to-top" role="button" aria-label="返回顶部">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>
  <a role="button" class="book-mark-link book-mark-link-fixed"></a>

<noscript>
  <div class="noscript-warning">Theme NexT works best with JavaScript enabled</div>
</noscript>


    <div class="main-inner post posts-expand">


  


<div class="post-block">
  
  

  <article itemscope itemtype="http://schema.org/Article" class="post-content" lang="zh-CN">
    <link itemprop="mainEntityOfPage" href="https://gz1234.gitee.io/2020/10/22/react%E7%AC%94%E8%AE%B0/React%E8%B7%AF%E7%94%B1/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="郭泽">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="郭泽">
      <meta itemprop="description" content="">
    </span>

    <span hidden itemprop="post" itemscope itemtype="http://schema.org/CreativeWork">
      <meta itemprop="name" content="react 路由的使用 | 郭泽">
      <meta itemprop="description" content="">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          react 路由的使用
        </h1>

        <div class="post-meta-container">
          <div class="post-meta">
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar"></i>
      </span>
      <span class="post-meta-item-text">发表于</span>

      <time title="创建时间：2020-10-22 10:07:09" itemprop="dateCreated datePublished" datetime="2020-10-22T10:07:09+08:00">2020-10-22</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-calendar-check"></i>
      </span>
      <span class="post-meta-item-text">更新于</span>
      <time title="修改时间：2021-10-13 18:11:55" itemprop="dateModified" datetime="2021-10-13T18:11:55+08:00">2021-10-13</time>
    </span>
    <span class="post-meta-item">
      <span class="post-meta-item-icon">
        <i class="far fa-folder"></i>
      </span>
      <span class="post-meta-item-text">分类于</span>
        <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
          <a href="/categories/react/" itemprop="url" rel="index"><span itemprop="name">react</span></a>
        </span>
    </span>

  
</div>

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">
        <h2 id="路由的使用"><a href="#路由的使用" class="headerlink" title="路由的使用"></a>路由的使用</h2><p>本章我们来介绍react中路由的使用,现在使用的路由是React-Router-4版本,我们需要下载的包叫react-router-dom</p>
<h3 id="安装"><a href="#安装" class="headerlink" title="安装"></a>安装</h3><figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">npm install react-router-dom</span><br></pre></td></tr></table></figure>
<a id="more"></a>
<blockquote>
<p>这里我们下载好后需要他内部的路由容器组件,主要包含BrowserRouter,HashRouter,MemoryRouter</p>
</blockquote>
<h3 id="容器组件的区别"><a href="#容器组件的区别" class="headerlink" title="容器组件的区别"></a>容器组件的区别</h3><ul>
<li>BrowserRouter: 浏览器自带的H5 API,restful风格,需要配合后台；</li>
<li>HashRouter: 使用hash方式进行路由,路径后均有#；</li>
<li>MemoryRouter: 在内存中管理history，地址栏不会变化。在reactNative中使用。</li>
</ul>
<blockquote>
<p>在开发时我们一般使用HashRouter,上线后我们改用BrowserRouter</p>
</blockquote>
<h3 id="跑通基本路由"><a href="#跑通基本路由" class="headerlink" title="跑通基本路由"></a>跑通基本路由</h3><p>我们来声明三个组件Home,User,Profile希望访问不同的路径可以实现显示不同的组件</p>
<figure class="highlight javascript"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">import</span> React <span class="keyword">from</span> <span class="string">&#x27;react&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> ReactDOM <span class="keyword">from</span> <span class="string">&#x27;react-dom&#x27;</span>;</span><br><span class="line"><span class="keyword">import</span> &#123;HashRouter,Route&#125; <span class="keyword">from</span> <span class="string">&#x27;react-router-dom&#x27;</span>;</span><br><span class="line"><span class="keyword">let</span> Home = <span class="function">() =&gt;</span><span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>home<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="keyword">let</span> Profile = <span class="function">() =&gt;</span><span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>Profile<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line"><span class="keyword">let</span> User = <span class="function">() =&gt;</span><span class="xml"><span class="tag">&lt;<span class="name">div</span>&gt;</span>User<span class="tag">&lt;/<span class="name">div</span>&gt;</span></span></span><br><span class="line">ReactDOM.render(&lt;HashRouter&gt;</span><br><span class="line">    &lt;div&gt;</span><br><span class="line">        &lt;Route path=<span class="string">&quot;/home&quot;</span> component=&#123;Home&#125;/&gt;</span><br><span class="line">        &lt;Route path=<span class="string">&quot;/profile&quot;</span> component=&#123;Profile&#125;/&gt;</span><br><span class="line">        &lt;Route path=<span class="string">&quot;/user&quot;</span> component=&#123;User&#125;/&gt;</span><br><span class="line">    &lt;/div&gt;</span><br><span class="line">&lt;/HashRouter&gt;,<span class="built_in">document</span>.querySelector(<span class="string">&#x27;#root&#x27;</span>));</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里我们使用了HashRouter,代码一目了然,这里用到了Route组件,Route组件上有path和component属性,对应的path会显示对应的component,这里还需注意HashRouter必须只能包含一个根元素,所以我们在所有的Route外层包了一个div标签</p>
</blockquote>
<h3 id="路由的匹配"><a href="#路由的匹配" class="headerlink" title="路由的匹配"></a>路由的匹配</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;div&gt;</span><br><span class="line">    &lt;Route path&#x3D;&quot;&#x2F;home&quot; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">    &lt;Route path&#x3D;&quot;&#x2F;profile&quot; component&#x3D;&#123;Profile&#125;&#x2F;&gt;</span><br><span class="line">    &lt;Route path&#x3D;&quot;&#x2F;profile&#x2F;user&quot; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">&lt;&#x2F;div&gt;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里我们稍作了下更改当访问/profile/user时你会发现/profile路由也会命中。所以说明只要路径开头匹配成功既会显示对应的组件,假如你希望不管访问任何路径时都能显示某一个组件你可以将path写成’/‘</p>
</blockquote>
<h3 id="Link组件"><a href="#Link组件" class="headerlink" title="Link组件"></a>Link组件</h3><p>我们先来引入bootstrap,将刚才的代码逻辑进行拆分,增加导航条点击不同的导航显示不同的组件。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">import ReactDOM from &#39;react-dom&#39;;</span><br><span class="line">import &#123;HashRouter,Route&#125; from &#39;react-router-dom&#39;;</span><br><span class="line">import &#39;bootstrap&#x2F;dist&#x2F;css&#x2F;bootstrap.css&#39;;</span><br><span class="line">import App from &#39;.&#x2F;App&#39;;</span><br><span class="line">import Home from &#39;.&#x2F;components&#x2F;Home&#39;;</span><br><span class="line">import Profile from &#39;.&#x2F;components&#x2F;Profile&#39;;</span><br><span class="line">import User from &#39;.&#x2F;components&#x2F;User&#39;;</span><br><span class="line">ReactDOM.render(&lt;HashRouter&gt;</span><br><span class="line">    &lt;App&gt;</span><br><span class="line">        &lt;Route path&#x3D;&quot;&#x2F;home&quot; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">        &lt;Route path&#x3D;&quot;&#x2F;profile&quot; component&#x3D;&#123;Profile&#125;&#x2F;&gt;</span><br><span class="line">        &lt;Route path&#x3D;&quot;&#x2F;user&quot; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">    &lt;&#x2F;App&gt;</span><br><span class="line">&lt;&#x2F;HashRouter&gt;,document.querySelector(&#39;#root&#39;));</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里我们增加了App组件,为什么这样做呢?原因是我们并不希望将所有的逻辑都写在index中,这并不方便我们的管理,还记得children属性吗？我们可以直接在App中通过children的方式引入</p>
</blockquote>
<h3 id="增加导航"><a href="#增加导航" class="headerlink" title="增加导航"></a>增加导航</h3><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">import &#123;Link&#125; from &#39;react-router-dom&#39;;</span><br><span class="line">export default class App extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;div className&#x3D;&quot;navbar-inverse navbar&quot;&gt;</span><br><span class="line">                    &lt;div className&#x3D;&quot;container-fluid&quot;&gt;</span><br><span class="line">                        &lt;div className&#x3D;&quot;navbar-header&quot;&gt;</span><br><span class="line">                            &lt;div className&#x3D;&quot;navbar-brand&quot;&gt;</span><br><span class="line">                                用户管理系统</span><br><span class="line">                            &lt;&#x2F;div&gt;</span><br><span class="line">                        &lt;&#x2F;div&gt;</span><br><span class="line">                        &lt;ul className&#x3D;&quot;navbar-nav nav&quot;&gt;</span><br><span class="line">                            &lt;li&gt;</span><br><span class="line">                                &lt;Link to&#x3D;&#123;&#39;&#x2F;home&#39;&#125;&gt;首页&lt;&#x2F;Link&gt;</span><br><span class="line">                            &lt;&#x2F;li&gt;</span><br><span class="line">                            &lt;li&gt;</span><br><span class="line">                                &lt;Link to&#x3D;&#123;&#39;&#x2F;user&#39;&#125;&gt;用户管理&lt;&#x2F;Link&gt;</span><br><span class="line">                            &lt;&#x2F;li&gt;</span><br><span class="line">                            &lt;li&gt;</span><br><span class="line">                                &lt;Link to&#x3D;&#123;&#39;&#x2F;profile&#39;&#125;&gt;个人中心&lt;&#x2F;Link&gt;</span><br><span class="line">                            &lt;&#x2F;li&gt;</span><br><span class="line">                        &lt;&#x2F;ul&gt;</span><br><span class="line">                    &lt;&#x2F;div&gt;</span><br><span class="line">                &lt;&#x2F;div&gt;</span><br><span class="line">                &lt;div className&#x3D;&quot;container&quot;&gt;</span><br><span class="line">                    &lt;div className&#x3D;&quot;row&quot;&gt;</span><br><span class="line">                        &lt;div className&#x3D;&quot;col-md-12&quot;&gt;</span><br><span class="line">                            &#123;this.props.children&#125;</span><br><span class="line">                        &lt;&#x2F;div&gt;</span><br><span class="line">                    &lt;&#x2F;div&gt;</span><br><span class="line">                &lt;&#x2F;div&gt;</span><br><span class="line">            &lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里使用Link组件它可以替代我们自己写的a标签,因为后面我们可能会用到browserHistory，跳转可能需要用到H5的api进行跳转,Link组件是react路由中提供的声明式组件,可以帮我们区分路由的模式来实现路由的跳转。</p>
</blockquote>
<h3 id="页面级组件"><a href="#页面级组件" class="headerlink" title="页面级组件"></a>页面级组件</h3><p>这里我们先将对应的组件代码代码贴出来,后面我们来完善对用的逻辑</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; Home.js</span><br><span class="line">import React from &#39;react&#39;;</span><br><span class="line">export default class Home extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;Home&lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; Profile.js</span><br><span class="line">import React from &#39;react&#39;;</span><br><span class="line">export default class Profile extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;Profile&lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; User.js</span><br><span class="line">import React from &#39;react&#39;;</span><br><span class="line">export default class User extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;User&lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<h3 id="二级路由"><a href="#二级路由" class="headerlink" title="二级路由"></a>二级路由</h3><p>刚才我们实现了一级导航,但是一般情况下管理系统都会拥有二级导航,比如说我们希望用户管理中包含用户列表和添加用户,这两个菜单应该属于用户列表下的子导航,我们先来看下效果</p>
<h4 id="实现二级路由"><a href="#实现二级路由" class="headerlink" title="实现二级路由"></a>实现二级路由</h4><p>二级导航就是在某个一级路由中继续嵌套路由</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">import &#123;Route,Link&#125; from &#39;react-router-dom&#39;</span><br><span class="line">import UserList from &#39;.&#x2F;UserList&#39;</span><br><span class="line">import UserAdd from &#39;.&#x2F;UserAdd&#39;</span><br><span class="line">export default class User extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div className&#x3D;&quot;row&quot;&gt;</span><br><span class="line">                &lt;div className&#x3D;&quot;col-md-2&quot;&gt;</span><br><span class="line">                    &lt;div className&#x3D;&quot;nav nav-stacked&quot;&gt;</span><br><span class="line">                        &lt;li&gt;&lt;Link to&#x3D;&#39;&#x2F;user&#x2F;list&#39;&gt;用户列表&lt;&#x2F;Link&gt;&lt;&#x2F;li&gt;</span><br><span class="line">                        &lt;li&gt;&lt;Link to&#x3D;&#39;&#x2F;user&#x2F;add&#39;&gt;增加用户&lt;&#x2F;Link&gt;&lt;&#x2F;li&gt;</span><br><span class="line">                    &lt;&#x2F;div&gt;</span><br><span class="line">                &lt;&#x2F;div&gt;</span><br><span class="line">                &lt;div className&#x3D;&quot;col-md-10&quot;&gt;</span><br><span class="line">                    &lt;Route path&#x3D;&quot;&#x2F;user&#x2F;list&quot; component&#x3D;&#123;UserList&#125;&#x2F;&gt;</span><br><span class="line">                    &lt;Route path&#x3D;&quot;&#x2F;user&#x2F;add&quot; component&#x3D;&#123;UserAdd&#125;&#x2F;&gt;</span><br><span class="line">                &lt;&#x2F;div&gt;</span><br><span class="line">            &lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里并没有什么需要注意的新用法,只是路径要特殊处理一下因为是二级路由,要保证一级路由也同时显示所以开头要和一级路由路径相同。如果多次点击相同路由时会触发<code>Hash history cannot PUSH the same path;</code>这样的一个警告,这个是无法去除的但是改成BrowserHistory就不会触发此警告了。所有不用担心.</p>
</blockquote>
<h4 id="UserList和Add组件"><a href="#UserList和Add组件" class="headerlink" title="UserList和Add组件"></a>UserList和Add组件</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">&#x2F;&#x2F; UserList.js</span><br><span class="line">import React from &#39;react&#39;;</span><br><span class="line">export default class UserList extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;UserList&lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line">&#x2F;&#x2F; UserAdd.js</span><br><span class="line">import React from &#39;react&#39;;</span><br><span class="line">export default class UserAdd extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;UserAdd&lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里我们先不写任何逻辑，先将具体的功能实现出来。这样我们就实现了二级路。</p>
</blockquote>
<h3 id="路由跳转和路径参数"><a href="#路由跳转和路径参数" class="headerlink" title="路由跳转和路径参数"></a>路由跳转和路径参数</h3><p>本节我们完善一下内部的逻辑,进入到添加列表页可以实现用户的添加并且可以跳转到列表页面渲染出添加的用户列表,页面间的通信我们采用localStorage。并且点击某个用户可以进入到用户详情页。</p>
<h4 id="实现添加用户"><a href="#实现添加用户" class="headerlink" title="实现添加用户"></a>实现添加用户</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">export default class UserAdd extends React.Component&#123;</span><br><span class="line">    handleSubmit &#x3D; (e) &#x3D;&gt;&#123;</span><br><span class="line">        e.preventDefault();</span><br><span class="line">        let localStr &#x3D; localStorage.getItem(&#39;lists&#39;);</span><br><span class="line">        let list &#x3D; JSON.parse(localStr)|| [];</span><br><span class="line">        list.push(&#123;id:Math.random(),name:this.name.value&#125;);</span><br><span class="line">        localStorage.setItem(&#39;lists&#39;,JSON.stringify(list));</span><br><span class="line">        this.props.history.push(&#39;&#x2F;user&#x2F;list&#39;)</span><br><span class="line">    &#125;;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;form onSubmit&#x3D;&#123;this.handleSubmit&#125;&gt;</span><br><span class="line">                    &lt;div className&#x3D;&quot;form-group&quot;&gt;</span><br><span class="line">                        &lt;label htmlFor&#x3D;&quot;name&quot; className&#x3D;&quot;control-label&quot;&gt;</span><br><span class="line">                            用户名:</span><br><span class="line">                        &lt;&#x2F;label&gt;</span><br><span class="line">                        &lt;input type&#x3D;&quot;text&quot; className&#x3D;&quot;form-control&quot; ref&#x3D;&#123;x&#x3D;&gt;this.name &#x3D; x&#125;&#x2F;&gt;</span><br><span class="line">                    &lt;&#x2F;div&gt;</span><br><span class="line">                    &lt;div className&#x3D;&quot;form-group&quot;&gt;</span><br><span class="line">                        &lt;button className&#x3D;&quot;btn btn-primary&quot;&gt;添加&lt;&#x2F;button&gt;</span><br><span class="line">                    &lt;&#x2F;div&gt;</span><br><span class="line">                &lt;&#x2F;form&gt;</span><br><span class="line">            &lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里我们在props中使用了history的API,所有通过路由渲染的组件都拥有一些路由的属性后面我们会一一介绍到。这里我们采用编程式的方式跳转了路径。</p>
</blockquote>
<h4 id="列表页展示"><a href="#列表页展示" class="headerlink" title="列表页展示"></a>列表页展示</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">import &#123;Link&#125; from &#39;react-router-dom&#39;</span><br><span class="line">export default class UserList extends React.Component&#123;</span><br><span class="line">    constructor()&#123;</span><br><span class="line">        super();</span><br><span class="line">        this.state &#x3D; &#123;&#125;</span><br><span class="line">    &#125;</span><br><span class="line">    componentWillMount()&#123;</span><br><span class="line">        let userList &#x3D; JSON.parse(localStorage.getItem(&#39;lists&#39;));</span><br><span class="line">        this.setState(&#123;</span><br><span class="line">            userList</span><br><span class="line">        &#125;)</span><br><span class="line">    &#125;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;ul className&#x3D;&quot;list-group&quot;&gt;</span><br><span class="line">                    &#123;this.state.userList.map((user,index)&#x3D;&gt;(</span><br><span class="line">                        &lt;li className&#x3D;&quot;list-group-item&quot; key&#x3D;&#123;index&#125;&gt;</span><br><span class="line">                            &lt;Link to&#x3D;&#123;&quot;&#x2F;user&#x2F;detail&#x2F;&quot;+user.id&#125;&gt;&#123;user.name&#125;&lt;&#x2F;Link&gt;</span><br><span class="line">                        &lt;&#x2F;li&gt;</span><br><span class="line">                    ))&#125;</span><br><span class="line">                &lt;&#x2F;ul&gt;</span><br><span class="line">            &lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里的逻辑比较简单,我们又添加了一个detail路径同样也是一个二级路由，点击用户名可以显示具体的用户id和用户名。</p>
</blockquote>
<h4 id="引入UserDetail组件"><a href="#引入UserDetail组件" class="headerlink" title="引入UserDetail组件"></a>引入UserDetail组件</h4><figure class="highlight diff"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"><span class="addition">+ import UserDetail from &#x27;./UserDetail&#x27;;</span></span><br><span class="line">  &lt;Route path=&quot;/user/list&quot; component=&#123;UserList&#125;/&gt;</span><br><span class="line">  &lt;Route path=&quot;/user/add&quot; component=&#123;UserAdd&#125;/&gt;</span><br><span class="line"><span class="addition">+ &lt;Route path=&quot;/user/detail/:id&quot; component=&#123;UserDetail&#125;/&gt;</span></span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里我们采用了模糊匹配的方式,这就是我们常说的路径参数。也就是说id可以代表任何值，我们可以在详情页中通过this.props.match.params.id获取到真实传入的id</p>
</blockquote>
<h4 id="UserDetail详情页"><a href="#UserDetail详情页" class="headerlink" title="UserDetail详情页"></a>UserDetail详情页</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">export default class UserDetail extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        let &#123;id &#125; &#x3D; this.props.match.params;</span><br><span class="line">        let &#123;name&#125; &#x3D; JSON.parse(localStorage.getItem(&#39;lists&#39;)).find(item&#x3D;&gt;item.id &#x3D;&#x3D; id);</span><br><span class="line">        return (</span><br><span class="line">            &lt;table className&#x3D;&quot;table table-bordered&quot;&gt;</span><br><span class="line">                &lt;thead&gt;</span><br><span class="line">                    &lt;tr&gt;</span><br><span class="line">                        &lt;th&gt;id号&lt;&#x2F;th&gt;</span><br><span class="line">                        &lt;th&gt;标题&lt;&#x2F;th&gt;</span><br><span class="line">                    &lt;&#x2F;tr&gt;</span><br><span class="line">                &lt;&#x2F;thead&gt;</span><br><span class="line">                &lt;tbody&gt;</span><br><span class="line">                    &lt;tr&gt;</span><br><span class="line">                        &lt;td&gt;&#123;id&#125;&lt;&#x2F;td&gt;</span><br><span class="line">                        &lt;td&gt;&#123;name&#125;&lt;&#x2F;td&gt;</span><br><span class="line">                    &lt;&#x2F;tr&gt;</span><br><span class="line">                &lt;&#x2F;tbody&gt;</span><br><span class="line">            &lt;&#x2F;table&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里要注意通过params取出的结果都是字符串类型,所有匹配到的参数都会放在match.params的属性上。</p>
</blockquote>
<h3 id="路由匹配"><a href="#路由匹配" class="headerlink" title="路由匹配"></a>路由匹配</h3><p>有的时候我们希望对路由匹配有些限制,比如说严格对某个路径进行匹配,或者匹配到某个路径时就不在匹配</p>
<h4 id="新增路由匹配"><a href="#新增路由匹配" class="headerlink" title="新增路由匹配"></a>新增路由匹配</h4><figure class="highlight diff"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">&lt;App&gt;</span><br><span class="line"><span class="addition">+       &lt;Route path=&quot;/&quot; render=&#123;()=&gt;&lt;h1&gt;首页&lt;/h1&gt;&#125;/&gt;</span></span><br><span class="line"><span class="addition">+       &lt;Route path=&quot;/:name&quot; render=&#123;()=&gt;&lt;h1&gt;zfpx&lt;/h1&gt;&#125;/&gt;</span></span><br><span class="line">        &lt;Route path=&quot;/home&quot; component=&#123;Home&#125;/&gt;</span><br><span class="line">        &lt;Route path=&quot;/profile&quot; component=&#123;Profile&#125;/&gt;</span><br><span class="line">        &lt;Route path=&quot;/user&quot; component=&#123;User&#125;/&gt;</span><br><span class="line">&lt;/App&gt;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>在此我们会发现当访问/home时以上<code>首页</code>和<code>zfpx</code>和<code>home组件</code>都会访问到,而我们只希望在访问/时才会显示首页,我们可以在某个Route上增加exact属性</p>
</blockquote>
<h4 id="exact"><a href="#exact" class="headerlink" title="exact"></a>exact</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;Route path&#x3D;&quot;&#x2F;&quot; exact render&#x3D;&#123;()&#x3D;&gt;&lt;h1&gt;首页&lt;&#x2F;h1&gt;&#125;&#x2F;&gt;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>你会发现这样就实现啦~,只会当访问/时才可以匹配到。</p>
</blockquote>
<h4 id="Switch"><a href="#Switch" class="headerlink" title="Switch"></a>Switch</h4><p>但是现在访问/home时我们依然有两个组件会被匹配到，我们希望匹配到一个后就停止匹配，不在继续匹配下一个路由，我们可以使用Switch组件</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">import &#123;HashRouter,Route,Switch&#125; from &#39;react-router-dom&#39;;</span><br><span class="line">&lt;Switch&gt;</span><br><span class="line">    &lt;Route path&#x3D;&quot;&#x2F;&quot; exact render&#x3D;&#123;()&#x3D;&gt;&lt;h1&gt;首页&lt;&#x2F;h1&gt;&#125;&#x2F;&gt;</span><br><span class="line">    &lt;Route path&#x3D;&quot;&#x2F;:name&quot; render&#x3D;&#123;()&#x3D;&gt;&lt;h1&gt;首页&lt;&#x2F;h1&gt;&#125;&#x2F;&gt;</span><br><span class="line">    &lt;Route path&#x3D;&quot;&#x2F;home&quot; component&#x3D;&#123;Home&#125;&#x2F;&gt;</span><br><span class="line">    &lt;Route path&#x3D;&quot;&#x2F;profile&quot; component&#x3D;&#123;Profile&#125;&#x2F;&gt;</span><br><span class="line">    &lt;Route path&#x3D;&quot;&#x2F;user&quot; component&#x3D;&#123;User&#125;&#x2F;&gt;</span><br><span class="line">&lt;&#x2F;Switch&gt;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>现在访问/home你会发现Home组件永远都不会显示出来啦！</p>
</blockquote>
<h3 id="受保护的路由"><a href="#受保护的路由" class="headerlink" title="受保护的路由"></a>受保护的路由</h3><p>我们想对一些路由进行屏蔽,例如登录后才能访问,这里我们在本地存一个变量来表示是否登录,增加一个登录路由，点击登录按钮将本地变量改为登录成功状态,即可以访问用户列表页面</p>
<h3 id="受保护路由"><a href="#受保护路由" class="headerlink" title="受保护路由"></a>受保护路由</h3><p>我们匹配到/user路由时要根据状态判断是否有权限，如果没权限需要跳转到登录页面，主要靠的是高阶组件的思想来实现:</p>
<h4 id="Protected组件"><a href="#Protected组件" class="headerlink" title="Protected组件"></a>Protected组件</h4><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">import &#123;Route,Redirect&#125; from &#39;react-router-dom&#39;</span><br><span class="line">export default (&#123;component:Component,...others&#125;)&#x3D;&gt;&#123;</span><br><span class="line">   return &lt;Route &#123;...others&#125; render&#x3D;&#123;(props)&#x3D;&gt;&#123;</span><br><span class="line">       return localStorage.getItem(&#39;loginSystem&#39;)?&lt;Component &#123;...props&#125;&#x2F;&gt;:&lt;Redirect to&#x3D;&#123;&#123;</span><br><span class="line">           pathname:&#39;&#x2F;login&#39;,</span><br><span class="line">           from:props.match.url</span><br><span class="line">       &#125;&#125;&#x2F;&gt;</span><br><span class="line">   &#125;&#125;&#x2F;&gt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>Redirect组件是用来重定向的，我们新增from属性来记录当前匹配的url,为了保证登录后可以在跳回到当前匹配的路径</p>
</blockquote>
<h4 id="新增Login组件"><a href="#新增Login组件" class="headerlink" title="新增Login组件"></a>新增Login组件</h4><figure class="highlight diff"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br></pre></td><td class="code"><pre><span class="line">&lt;div className=&quot;container&quot;&gt;</span><br><span class="line">    &lt;Route path=&quot;/home&quot; component=&#123;Home&#125;/&gt;</span><br><span class="line"><span class="deletion">-   &lt;Route path=&quot;/profile&quot; component=&#123;Profile&#125;/&gt;</span></span><br><span class="line"><span class="addition">+   &lt;PrivateRoute path=&quot;/profile&quot; component=&#123;Profile&#125;/&gt;</span></span><br><span class="line">    &lt;Route path=&quot;/user&quot; component=&#123;User&#125;/&gt;</span><br><span class="line"><span class="addition">+   &lt;Route path=&quot;/login&quot; component=&#123;Login&#125;/&gt;</span></span><br><span class="line">&lt;/div&gt;</span><br><span class="line"></span><br><span class="line">Login.js</span><br><span class="line">import React from &#x27;react&#x27;;</span><br><span class="line">export default class Login extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;</span><br><span class="line">                &lt;button className=&quot;btn btn-primary&quot; onClick=&#123;()=&gt;&#123;</span><br><span class="line">                    window.localStorage.setItem(&#x27;loginSystem&#x27;,true);</span><br><span class="line">                   this.props.history.push(this.props.location.from)</span><br><span class="line">                &#125;&#125;&gt;登录&lt;/button&gt;</span><br><span class="line">            &lt;/div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>我们发现默认点击profile会默认跳转到login组件中，点击登录可以再次跳回profile。这样我们就实现了受保护的路由。</p>
</blockquote>
<h3 id="自定义菜单"><a href="#自定义菜单" class="headerlink" title="自定义菜单"></a>自定义菜单</h3><p>我们想给点击后的菜单增加激活样式，同样依然采用高阶组件的方式进行包装</p>
<h4 id="实现MenuLink组件"><a href="#实现MenuLink组件" class="headerlink" title="实现MenuLink组件"></a>实现MenuLink组件</h4><p>此组件是用来替换掉原有的Link组件，并且在内部进行判断是否增加激活状态</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">import &#123;Route,Link&#125; from &#39;react-router-dom&#39;</span><br><span class="line">export default (&#123;to,label&#125;)&#x3D;&gt;&#123;</span><br><span class="line">    return &lt;Route children&#x3D;&#123;(props)&#x3D;&gt;&#123;</span><br><span class="line">        return &lt;li className&#x3D;&#123;props.match?&#39;active&#39;:&#39;&#39;&#125;&gt;&lt;Link to&#x3D;&#123;to&#125;&gt;&#123;label&#125;&lt;&#x2F;Link&gt;&lt;&#x2F;li&gt;</span><br><span class="line">    &#125;&#125;&#x2F;&gt;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里有个children属性和以前render不同，children无论是否路由匹配到都会执行此函数。而render只要在匹配到后才会执行</p>
</blockquote>
<h3 id="Prompt"><a href="#Prompt" class="headerlink" title="Prompt"></a>Prompt</h3><p>我们希望在添加页的输入框中输入内容后点击其他路由时先询问一下是否需要跳转。</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line">constructor()&#123;</span><br><span class="line">    super();</span><br><span class="line">    this.state &#x3D; &#123;show:false&#125;</span><br><span class="line">&#125;</span><br><span class="line">&lt;div&gt;</span><br><span class="line">    &lt;Prompt when&#x3D;&#123;this.state.show&#125; message&#x3D;&#123;location &#x3D;&gt; (</span><br><span class="line">        &#96;Are you sure you want to go to $&#123;location.pathname&#125;?&#96;</span><br><span class="line">    )&#125;&#x2F;&gt;</span><br><span class="line">    &lt;form onSubmit&#x3D;&#123;this.handleSubmit&#125;&gt;</span><br><span class="line">        &lt;div className&#x3D;&quot;form-group&quot;&gt;</span><br><span class="line">            &lt;label htmlFor&#x3D;&quot;username&quot;&gt;用户名&lt;&#x2F;label&gt;</span><br><span class="line">            &lt;input type&#x3D;&quot;text&quot; className&#x3D;&quot;form-control&quot; ref&#x3D;&#123;(x)&#x3D;&gt;this.x&#x3D;x&#125;</span><br><span class="line">               onChange&#x3D;&#123;(e)&#x3D;&gt;&#123;</span><br><span class="line">                   if(e.target.value.length&gt;0)&#123;</span><br><span class="line">                       this.setState(&#123;show:true&#125;)</span><br><span class="line">                   &#125;</span><br><span class="line">               &#125;</span><br><span class="line">            &#x2F;&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;</span><br><span class="line">        &lt;div className&#x3D;&quot;form-group&quot;&gt;</span><br><span class="line">            &lt;button className&#x3D;&quot;btn btn-primary&quot; &gt;添加&lt;&#x2F;button&gt;</span><br><span class="line">        &lt;&#x2F;div&gt;</span><br><span class="line">    &lt;&#x2F;form&gt;</span><br><span class="line">&lt;&#x2F;div&gt;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>监听输入框中的内容,当有内容时将状态show变为true,当需要跳转路由时Prompt的组件when属性为true就会提示对应的message,当然我们点击添加时不需要弹出,所以先将状态改为false在进行跳转即可。</p>
</blockquote>
<figure class="highlight diff"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">handleSubmit=(e)=&gt;&#123;</span><br><span class="line">    e.preventDefault();</span><br><span class="line">    let list = JSON.parse(localStorage.getItem(&#x27;lists&#x27;))||[];</span><br><span class="line">    list.push(&#123;id:Math.random(),name:this.x.value&#125;);</span><br><span class="line">    localStorage.setItem(&#x27;lists&#x27;,JSON.stringify(list));</span><br><span class="line"><span class="addition">+   this.setState(&#123;show:false&#125;,()=&gt;&#123;</span></span><br><span class="line">        this.props.history.push(&#x27;/profile/list&#x27;)</span><br><span class="line"><span class="addition">+   &#125;)</span></span><br><span class="line">&#125;;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>要等待状态改变后在执行跳转，因为setState是异步的所以要将跳转逻辑放的回调函数中。</p>
</blockquote>
<h2 id="NotFound页面"><a href="#NotFound页面" class="headerlink" title="NotFound页面"></a>NotFound页面</h2><p>我们需要当路由都匹配不到时显示一个404页面,增加一个404组件</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">import React from &#39;react&#39;;</span><br><span class="line">export default class NotFound extends React.Component&#123;</span><br><span class="line">    render()&#123;</span><br><span class="line">        return (</span><br><span class="line">            &lt;div&gt;NotFound&lt;&#x2F;div&gt;</span><br><span class="line">        )</span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<h3 id="新增404路由"><a href="#新增404路由" class="headerlink" title="新增404路由"></a>新增404路由</h3><figure class="highlight diff"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;div className=&quot;container&quot;&gt;</span><br><span class="line">    &lt;Switch&gt;</span><br><span class="line">        &lt;Route path=&quot;/home&quot; component=&#123;Home&#125;/&gt;</span><br><span class="line">        &lt;PrivateRoute path=&quot;/profile&quot; component=&#123;Profile&#125;/&gt;</span><br><span class="line">        &lt;Route path=&quot;/user&quot; component=&#123;User&#125;/&gt;</span><br><span class="line">        &lt;Route path=&quot;/login&quot; component=&#123;Login&#125;/&gt;</span><br><span class="line"><span class="addition">+       &lt;Route component=&#123;NotFound&#125;/&gt;</span></span><br><span class="line">    &lt;/Switch&gt;</span><br><span class="line">&lt;/div&gt;</span><br></pre></td></tr></table></figure>

<blockquote>
<p>这里我们使用switch组件当全部匹配不到时会默认渲染404路由,这样我们就实现了404页面</p>
</blockquote>
<script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kity@2.0.4/dist/kity.min.js"></script><script type="text/javascript" src="https://cdn.jsdelivr.net/npm/kityminder-core@1.4.50/dist/kityminder.core.min.js"></script><script defer="true" type="text/javascript" src="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.js"></script><link rel="stylesheet" type="text/css" href="https://cdn.jsdelivr.net/npm/hexo-simple-mindmap@0.2.0/dist/mindmap.min.css">
    </div>

    
    
    

    <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/react-%E5%9F%BA%E7%A1%80/" rel="tag"># react 基础</a>
          </div>

        

          <div class="post-nav">
            <div class="post-nav-item">
                <a href="/2020/10/21/react%E7%AC%94%E8%AE%B0/React%E5%9F%BA%E7%A1%80%E7%AF%87/" rel="prev" title="react 基础">
                  <i class="fa fa-chevron-left"></i> react 基础
                </a>
            </div>
            <div class="post-nav-item">
                <a href="/2020/10/23/react%E7%AC%94%E8%AE%B0/Redux%E5%BA%94%E7%94%A8/" rel="next" title="Redux">
                  Redux <i class="fa fa-chevron-right"></i>
                </a>
            </div>
          </div>
    </footer>
  </article>
</div>






</div>
  </main>

  <footer class="footer">
    <div class="footer-inner">


<div class="copyright">
  &copy; 
  <span itemprop="copyrightYear">2023</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">郭泽</span>
</div>
  <div class="powered-by">由 <a href="https://hexo.io/" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.js.org/" rel="noopener" target="_blank">NexT.Gemini</a> 强力驱动
  </div>

    </div>
  </footer>

  
  <script src="https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.1/anime.min.js" integrity="sha256-XL2inqUJaslATFnHdJOi9GfQ60on8Wx1C2H8DYiN1xY=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fancybox/3.5.7/jquery.fancybox.min.js" integrity="sha256-yt2kYMy0w8AbtF89WXb2P1rfjcP/HTHLT7097U8Y5b8=" crossorigin="anonymous"></script>
<script src="/js/comments.js"></script><script src="/js/utils.js"></script><script src="/js/motion.js"></script><script src="/js/next-boot.js"></script><script src="/js/bookmark.js"></script>

  
<script src="https://cdnjs.cloudflare.com/ajax/libs/hexo-generator-searchdb/1.4.0/search.js" integrity="sha256-vXZMYLEqsROAXkEw93GGIvaB2ab+QW6w3+1ahD9nXXA=" crossorigin="anonymous"></script>
<script src="/js/third-party/search/local-search.js"></script>

  <script class="next-config" data-name="pdf" type="application/json">{"object_url":{"url":"https://cdnjs.cloudflare.com/ajax/libs/pdfobject/2.2.8/pdfobject.min.js","integrity":"sha256-tu9j5pBilBQrWSDePOOajCUdz6hWsid/lBNzK4KgEPM="},"url":"/lib/pdf/web/viewer.html"}</script>
  <script src="/js/third-party/tags/pdf.js"></script>

  <script class="next-config" data-name="mermaid" type="application/json">{"enable":true,"theme":{"light":"default","dark":"dark"},"js":{"url":"https://cdnjs.cloudflare.com/ajax/libs/mermaid/9.1.3/mermaid.min.js","integrity":"sha256-TIYL00Rhw/8WaoUhYTLX9SKIEFdXxg+yMWSLVUbhiLg="}}</script>
  <script src="/js/third-party/tags/mermaid.js"></script>

  <script src="/js/third-party/fancybox.js"></script>


  





</body>
</html>
